package org.jw.wishlist.resolver;

import static com.google.common.base.Preconditions.checkArgument;
import static org.apache.commons.lang3.ObjectUtils.isNotEmpty;

import java.util.List;
import java.util.Optional;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.jw.wishlist.entity.source.ItemSource;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;

/**
 * @author Jiawei Zhao
 */
@Slf4j
public class HpoiItemSourceResolver extends ItemSourceSupports implements ItemSourceResolver {

  private static final String SOURCE_KEY = "hpoi";

  public HpoiItemSourceResolver(RestTemplate restTemplate) {
    super(restTemplate);
  }

  private static String getPicUrl(String thumb) {

    UriComponents uc = UriComponentsBuilder.fromHttpUrl(thumb).build();

    UriComponentsBuilder b = UriComponentsBuilder.fromHttpUrl(thumb).replacePath("").replaceQuery("");

    boolean found = false;
    boolean replaced = false;
    for (String p : uc.getPathSegments()) {
      if (found && !replaced) {
        b.pathSegment("n");
        replaced = true;
        continue;
      }

      if ("pic".equals(p)) {
        found = true;
      }
      b.pathSegment(p);
    }

    return b.build().toString();
  }

  @Override
  public ItemSource resolve(String linkCode) {

    String url = extractUrl(linkCode);
    UriComponents uc = UriComponentsBuilder.fromHttpUrl(url)
        .build();
    checkArgument(isNotEmpty(uc.getPath())
            && uc.getPath().startsWith("/hobby"),
        "目前只支持收藏手办情报");

    List<String> segments = uc.getPathSegments();
    String itemId = segments.get(segments.size() - 1);

    String html = restTemplate.getForObject(url, String.class);
    checkArgument(isNotEmpty(html), "解析失败");
    Document document = Jsoup.parse(html);

    Elements items = document.select(".hpoi-infoList-item");
    String title = items.select(":contains(名称) > p").text();
    String price = items.select(":contains(定价) > p").text();
    String pic = Optional.ofNullable(document.select(".swiper-slide.hpoi-auto-width a img").first())
        .map(x -> x.attr("src"))
        .map(HpoiItemSourceResolver::getPicUrl)
        .orElseThrow(() -> new IllegalArgumentException("解析失败"));

    return new ProductItemSourceBuilder()
        .key(SOURCE_KEY)
        .itemId(itemId)
        .accessUrl(url)
        .originUrl(url)
        .linkCode(linkCode)
        .name(title)
        .price(price)
        .pictureUrl(pic)
        .build();
  }

}
